var system = {};
system.http = require('http');
system.events = require('events');
system.fs = require('fs');
system.url = require('url');

system.documentRoot = '/usr/local/zend/apache2/htdocs/node/';
system.charset = 'utf-8';
system.mimeTypes = {
    'html': 'text/html;charset=' + system.charset,
    'htm': 'text/html;charset=' + system.charset,
    'js': 'application/javascript;charset=' + system.charset,
    'css': 'text/css;charset=' + system.charset,
    'jpeg': 'image/jpeg',
    'jpg': 'image/jpeg',
    'jpe': 'image/jpeg',
    'png': 'image/png',
    'gif': 'image/gif'
};

/**
 * @param {String} path
 * @return {String}
 */
var securePath = function (path) {
    var array = path.split('.');
    var ext = array.pop();
    return array.join('') + '.' + ext;
};
/**
 * @param {String} string
 */
var getExtensions = function (string) {
    var ext = '';
    if (string.indexOf('.') !== -1) {
        ext = string.split('.').pop();
    }
    return ext;
};

system.http.createServer(function (request, response) {
    var url = system.url.parse(request.url, true);
    console.log(url);
    var pathname = securePath(url.pathname);

    var type = system.mimeTypes[getExtensions(pathname)];
    if (type) {
        //output file content direct
        if (system.fs.existsSync(system.documentRoot + pathname)) {
            response.writeHead(200, {'Content-Type': type});
            response.end(system.fs.readFileSync(system.documentRoot + pathname));
        } else {
            response.writeHead(404, {'Content-Type': 'text/plain;charset=' + system.charset});
            response.end('Not Found');
        }
    } else {
        response.writeHead(200, {'Content-Type': 'text/plain'});
        response.end('It works!');
    }
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
